package com.moleq.dialog;

import java.util.ArrayList;
import java.util.List;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AbsoluteLayout;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.moleq.base.MoleQBaseDialog;
import com.moleq.base.OnResultListener;
import com.moleq.base.SmartBeep;
import com.moleq.dialog.MessageDialog.OnClickMessageListener;
import com.moleq.itemsetting.tools.MGCreateFiles;
import com.moleq.logic.MoleQConstants;
import com.moleq.mgpos.activities.R;
import com.moleq.mgpos.widget.BeepImageButton;
import com.moleq.models.AgeSetting;
import com.moleq.models.GlobalInfo;
import com.moleq.service.AgeSettingService;
import com.moleq.service.ServiceManager;

public class AgeSelectionDialog extends Dialog implements OnResultListener {

	private OnResultListener mOnResultListener;
	private Context mContext;
	private List<AgeSetting> mDataSource = new  ArrayList<AgeSetting>();
	private OpenAgeAdapter mAdapter;
	private int selectedRow = 0;
	private  ListView lv_age_dialog_list;
	private Button  btn_age_dialog_ok, btn_age_dialog_cancel;
	private BeepImageButton iv_age_dialog_add, iv_age_dialog_ok, iv_age_dialog_delete, iv_age_dialog_update;
	private EditText et_age_name;
	private EditText et_age_value;
	private AbsoluteLayout al_age_dialog_perview_mode_layout;
	public AgeSettingService mAgeSettingService ;
	public static final int DIALOG_ADD = 0;
	public static final int DIALOG_OK = 1;
	public static int CurrentActionStatus = 0;
	private MGCreateFiles mMGCreateFiles = new MGCreateFiles();
	private String action = "";
	private String ls_original_age = "";
	private String ls_original_name = "";
	
	private Button.OnClickListener mOnClickListener = new Button.OnClickListener() {

		@Override
		public void onClick(View v) {	
			switch(v.getId()){
			case R.id.iv_age_dialog_add:
				AgeDialogUpdate(selectedRow);
				et_age_name.setText("");
				et_age_value.setText("");
				break;
			case R.id.iv_age_dialog_ok:
				AgeDialogUpdate(selectedRow);
				et_age_name.setText("");
				et_age_value.setText("");
				break;
			case R.id.iv_age_dialog_delete:
				if (mDataSource.size() <= 0)
					return;
				int age_no = mDataSource.get(selectedRow).getAs_no();

				if (!mAgeSettingService.CheckAgeByNO(String.valueOf(age_no))) {
					MessageBox.show(mContext, "The age selection cannot be removed beacause it is linked to items.", onClickMessageListener, MessageDialog.MESSAGE_BOX_OK);
					return;
				}
				if (!mAgeSettingService.CheckAgeByDepNo(age_no)) {
					MessageBox.show(mContext, "The age selection cannot be removed beacause it is linked to departments.", onClickMessageListener, MessageDialog.MESSAGE_BOX_OK);
					return;
				}
				if (!mAgeSettingService.CheckAgeBySubdepNo(age_no)) {
					MessageBox.show(mContext, "The age selection cannot be removed beacause it is linked to sub-departments.", onClickMessageListener, MessageDialog.MESSAGE_BOX_OK);
					return;
				}
				
				MessageBox.show(mContext, "Are you sure to delete the age entry?",onClickMessageListener,MessageDialog.MESSAGE_BOX_YES_NO);
				break;
			case R.id.iv_age_dialog_update:
				if (mDataSource.size() <= 0) {
					return;
				}
				action = "update";
				AgeDialogUpdate(selectedRow);
				String age_name = String.valueOf(mDataSource.get(selectedRow).getAs_desc());
				String age_value = String.valueOf(mDataSource.get(selectedRow).getAs_age());
				ls_original_age = age_value;
				ls_original_name = age_name;

				et_age_name.setText(age_name);
				et_age_value.setText(age_value);

				break;
			case R.id.btn_age_dialog_cancel:
				dismiss();
				break;
			case R.id.btn_age_dialog_ok:	
				if(mDataSource.size() <= 0){
					return;	
				}
				onCloseWithReturn(mDataSource.get(selectedRow));
				dismiss();
				break;
			}
		}
	};

	
	public void AgeDialogUpdate(int index) {
		AgeSetting as = new AgeSetting();
		CurrentActionStatus = Integer.valueOf((String) iv_age_dialog_add.getTag());
		if (CurrentActionStatus == DIALOG_ADD) {
			lv_age_dialog_list.setEnabled(false);
			btn_age_dialog_ok.setEnabled(false);
			btn_age_dialog_cancel.setEnabled(false);
			iv_age_dialog_delete.setEnabled(false);
			iv_age_dialog_update.setEnabled(false);
			et_age_name.setVisibility(View.VISIBLE);
			et_age_value.setVisibility(View.VISIBLE);
			iv_age_dialog_ok.setVisibility(View.VISIBLE);
			iv_age_dialog_add.setVisibility(View.GONE);
			iv_age_dialog_add.setTag(String.valueOf(DIALOG_OK));
		} else if (CurrentActionStatus == DIALOG_OK) {
			lv_age_dialog_list.setEnabled(true);
			btn_age_dialog_ok.setEnabled(true);
			btn_age_dialog_cancel.setEnabled(true);
			iv_age_dialog_delete.setEnabled(true);
			iv_age_dialog_update.setEnabled(true);
			et_age_name.setVisibility(View.INVISIBLE);
			et_age_value.setVisibility(View.INVISIBLE);
			iv_age_dialog_ok.setVisibility(View.GONE);
			iv_age_dialog_add.setVisibility(View.VISIBLE);
			iv_age_dialog_add.setTag(String.valueOf(DIALOG_ADD));

			if (!action.equals("update")) {
				action = "";
			}

			String Value = String.valueOf(et_age_value.getText());
			String name = String.valueOf(et_age_name.getText());
			AgeSetting age = null;
			String ls_age_no = "";
			if (mDataSource.size() > 0) {
				ls_age_no = String.valueOf(mDataSource.get(index).getAs_no());
				as.setAs_no(mDataSource.get(index).getAs_no());
			}

			if (Value != null && !Value.trim().equals("") && name != null && !name.trim().equals("")) {
				as.setAs_age(Integer.valueOf(Value));
				as.setAs_desc(name);

				if (action.equals("update") && !ls_age_no.equals("")) {
					action = "";
					if (ls_original_age.equals(Value) && ls_original_name.equals(name)) {
						return;
					}
					if (mAgeSettingService.CheckAge(Value, name) == false) {
						MessageBox.show(mContext,"The age was already exists.");
						return;
					}
					mAgeSettingService.Update(as);
					
					if (GlobalInfo.getInstance().isMGNetwork) {
						age = mAgeSettingService.Find(as.getAs_no());
						mMGCreateFiles.createrFile(age.toMGData("UPDATE"));//UPDATE,DELETE
					}

				} else {

					if (mAgeSettingService.CheckAge(Value, name) == false) {
						MessageBox.show(mContext,"The age was already exists.");
						
						return;
					}
					
					as.setAs_no(mAgeSettingService.getMaxNo() + 1);
					mAgeSettingService.Insert(as);
					
					if (GlobalInfo.getInstance().isMGNetwork) {
						age = mAgeSettingService.Find(as.getAs_no());
						mMGCreateFiles.createrFile(age.toMGData("INSERT"));//UPDATE,DELETE
					}
				}
				mDataSource = mAgeSettingService.FindAll();
				mAdapter.notifyDataSetChanged();
			}

			ScrollToRow(mDataSource.size() - 1);
			lv_age_dialog_list.setSelection(mDataSource.size() - 1);
		}

	}
	
	public ListView.OnItemClickListener onItemClickListener = new ListView.OnItemClickListener() {


		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {

			switch (parent.getId()) {
			case R.id.lv_age_dialog_list:
				ScrollToRow(position);
				break;
			}
		}
	};

	
	
	public void onCloseWithReturn(Object obj){
		mOnResultListener.onReturnValue(MoleQConstants.DIALOG_AGE_INFO,obj);
		dismiss();
	}
	
	public AgeSelectionDialog(Context context) {
		super(context,R.style.dialog2);
		constructor(context,context);
		
	}
	
	private void constructor(Context context,Object base) {
		mContext = context;
		mOnResultListener = (OnResultListener) base;
	}

	public AgeSelectionDialog(Context context, int theme) {
		super(context, theme);
		constructor(context);
	}
	
	private void constructor(Context context) {
		// TODO Auto-generated method stub
		mContext = context;
	}
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// set UI layout
		this.setContentView(R.layout.dept_age_dialog_perview_models);
		this.setCancelable(false);
	
		
		lv_age_dialog_list = (ListView) findViewById(R.id.lv_age_dialog_list);
		btn_age_dialog_ok = (Button) findViewById(R.id.btn_age_dialog_ok);
		btn_age_dialog_cancel = (Button) findViewById(R.id.btn_age_dialog_cancel);
		iv_age_dialog_add = (BeepImageButton) findViewById(R.id.iv_age_dialog_add);
		iv_age_dialog_ok = (BeepImageButton)findViewById(R.id.iv_age_dialog_ok);
		iv_age_dialog_delete = (BeepImageButton) findViewById(R.id.iv_age_dialog_delete);
		iv_age_dialog_update = (BeepImageButton) findViewById(R.id.iv_age_dialog_update);
		al_age_dialog_perview_mode_layout = (AbsoluteLayout) findViewById(R.id.al_age_dialog_perview_mode_layout);
		et_age_name = (EditText) findViewById(R.id.et_age_name);
		et_age_value = (EditText) findViewById(R.id.et_age_value);

		lv_age_dialog_list.setOnItemClickListener(onItemClickListener);
		btn_age_dialog_ok.setOnClickListener(mOnClickListener);
		btn_age_dialog_cancel.setOnClickListener(mOnClickListener);
		iv_age_dialog_add.setOnClickListener(mOnClickListener);
		iv_age_dialog_ok.setOnClickListener(mOnClickListener);
		iv_age_dialog_delete.setOnClickListener(mOnClickListener);
		iv_age_dialog_update.setOnClickListener(mOnClickListener);
		al_age_dialog_perview_mode_layout.setOnClickListener(mOnClickListener);

		mAdapter = new OpenAgeAdapter(mContext);
		lv_age_dialog_list.setAdapter(mAdapter);
	}
	
	public void show(String agetext){
		super.show();		
		mAgeSettingService = ServiceManager.getInstance().mAgeSettingService;
		mDataSource =  mAgeSettingService.FindAll();
		mAdapter.notifyDataSetChanged();
		ScrollToRow(GetAgePosition(agetext));
	}
	
	public int GetAgePosition(String AgeName) {
		int idx = -1;
		for (int i = 0; i < mDataSource.size(); i++) {
			idx = 0;
			AgeSetting age = mDataSource.get(i);
			if (age.getAs_desc().equals(AgeName)) {
				return i;
			}
		}
		return idx;
	}
	
	class OpenAgeAdapter extends BaseAdapter{
		private Context maContext;
		public final class ViewHolder{
			public TextView tv_itemsname;
			public TextView tv_itemsage;
		}
		
		public OpenAgeAdapter(Context context){
			maContext = context;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mDataSource.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return mDataSource.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ViewHolder holder = null;
			if(convertView == null){
				holder = new ViewHolder();
				convertView = LayoutInflater.from(maContext).inflate(R.layout.dept_chooseage, null);
				holder.tv_itemsname = (TextView) convertView.findViewById(R.id.tv_itemsname);
				holder.tv_itemsage = (TextView) convertView.findViewById(R.id.tv_itemsage);
				
				convertView.setTag(holder);
			}else{
				holder = (ViewHolder) convertView.getTag();
			}
//			
			holder.tv_itemsname.setText(mDataSource.get(position).getAs_desc());
			holder.tv_itemsage.setText(String.valueOf(mDataSource.get(position).getAs_age()));
			
			if (position == selectedRow) {
				holder.tv_itemsname.setBackgroundColor(Color.rgb(255,219,16));
				holder.tv_itemsage.setBackgroundColor(Color.rgb(255,219,16));
			} else {
				holder.tv_itemsname.setBackgroundColor(Color.rgb(204, 204, 204));
				holder.tv_itemsage.setBackgroundColor(Color.rgb(204, 204, 204));
			}
			
			return convertView;
		}
		
	}
	
	private OnTouchListener onItemTouchListener = new OnTouchListener(){

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			if(event.getAction() == MotionEvent.ACTION_DOWN){
				SmartBeep.getInstance().play(SmartBeep.SOUND_CLICK);
			}
			return false;
		}
		
	};
	
	public void ScrollToRow(int row){
		selectedRow = row;
		mAdapter.notifyDataSetChanged();
	}

	@Override
	public void onCloseWithReturn(Class<? extends MoleQBaseDialog> pramClass,
			int viewId, String returnvalue) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onReturnValue(int what, Object obj) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onShowingMessageDlg(boolean isShowing) {
		// TODO Auto-generated method stub
		
	}
	
	private OnClickMessageListener onClickMessageListener = new OnClickMessageListener() {

		@Override
		public void onClickYes() {
			// TODO Auto-generated method stub
			int position = selectedRow;
			int Value = mDataSource.get(position).getAs_no();
			if (GlobalInfo.getInstance().isMGNetwork) {
				AgeSetting age = mAgeSettingService.Find(Value);
				mMGCreateFiles.createrFile(age.toMGData("DELETE"));//UPDATE,DELETE
			}
			mAgeSettingService.DeleteAge(Value);
			mDataSource = mAgeSettingService.FindAll();
			mAdapter.notifyDataSetChanged();
			if (position > 0) {
				position = position - 1;
			}
			ScrollToRow(position);
		}

		@Override
		public void onClickNo() {
			
		}

		@Override
		public void onClickOK() {
			
		}

	};

}
